<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="优惠券名" prop="mid">
        <el-select v-model="queryParams.mid" placeholder="请选择商家名称" clearable style="width: 200px;">
          <el-option v-for="merchant in merchantList" :key="merchant.id" :label="merchant.name" :value="merchant.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable style="width: 200px;">
          <el-option label="折扣券" value="discount" />
          <el-option label="满减券" value="fullReduction" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="start">
        <el-date-picker clearable v-model="queryParams.start" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择开始时间" style="width: 200px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="isend">
        <el-date-picker clearable v-model="queryParams.isend" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择结束时间" style="width: 200px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="投放数量" prop="num">
        <el-input v-model="queryParams.num" placeholder="请输入投放数量" clearable @keyup.enter="handleQuery" style="width: 200px;"/>
      </el-form-item>
      <el-form-item label="领取数量" prop="size">
        <el-input v-model="queryParams.size" placeholder="请输入领取数量" clearable @keyup.enter="handleQuery" style="width: 200px;"/>
      </el-form-item>
      <el-form-item label="有限期始" prop="expirationStart">
        <el-date-picker clearable v-model="queryParams.expirationStart" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择有限期始" style="width: 200px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="有效期末" prop="expirationEnd">
        <el-date-picker clearable v-model="queryParams.expirationEnd" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择有效期末" style="width: 200px;" >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px;">
          <el-option label="未开始" value="0" />
          <el-option label="进行中" value="1" />
          <el-option label="已结束" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['chy:coupon:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['chy:coupon:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['chy:coupon:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['chy:coupon:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="优惠券号" align="center" prop="id" fixed="left" />
      <el-table-column label="商家名称" align="center" prop="mid">
        <template #default="scope">
          <span>{{ getMerchantNameById(scope.row.mid) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          <el-tag :type="getTypeTagType(scope.row.type)">
            {{ getTypeName(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="折扣额度" align="center" prop="discount" />
      <el-table-column label="使用门槛" align="center" prop="triggerMoney" width="130">
        <template #default="scope">
          <!-- 使用 el-tag 展示使用门槛数据 -->
          <el-tag type="warning">
            {{ scope.row.triggerMoney }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优惠金额" align="center" prop="preferentialMoney" />
      <el-table-column label="开始时间" align="center" prop="start" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.start, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="isend" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.isend, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="投放数量" align="center" prop="num" />
      <el-table-column label="领取数量" align="center" prop="size" />
      <el-table-column label="有限期始" align="center" prop="expirationStart" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expirationStart, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期末" align="center" prop="expirationEnd" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expirationEnd, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusName(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="130">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['chy:coupon:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['chy:coupon:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商优惠券对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="couponRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商家名称" prop="mid">
          <el-select v-model="form.mid" placeholder="请选择商家名称" @change="fillCouponName">
            <el-option v-for="merchant in merchantList" :key="merchant.id" :label="merchant.name"
              :value="merchant.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券名" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名" disabled />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="折扣券" value="discount" />
            <el-option label="满减券" value="fullReduction" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="折扣额度" prop="discount">
          <el-input v-model="form.discount" placeholder="请输入折扣额度" />
        </el-form-item>
        <el-form-item label="使用门槛" prop="triggerMoney">
          <el-input v-model="form.triggerMoney" placeholder="请输入使用门槛" />
        </el-form-item>
        <el-form-item label="优惠金额" prop="preferentialMoney">
          <el-input v-model="form.preferentialMoney" placeholder="请输入优惠金额" />
        </el-form-item>
        <el-form-item label="开始时间" prop="start">
          <el-date-picker clearable v-model="form.start" type="date" value-format="YYYY-MM-DD" placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="isend">
          <el-date-picker clearable v-model="form.isend" type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="投放数量" prop="num">
          <el-input v-model="form.num" placeholder="请输入投放数量" />
        </el-form-item>
        <el-form-item label="领取数量" prop="size">
          <el-input v-model="form.size" placeholder="请输入领取数量" />
        </el-form-item>
        <el-form-item label="有限期始" prop="expirationStart">
          <el-date-picker clearable v-model="form.expirationStart" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择有限期始">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期末" prop="expirationEnd">
          <el-date-picker clearable v-model="form.expirationEnd" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择有效期末">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="未开始" value="0" />
            <el-option label="进行中" value="1" />
            <el-option label="已结束" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Coupon">
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon } from "@/api/chy/coupon"
import { listMerchant } from "@/api/chy/merchant"

const { proxy } = getCurrentInstance()

const couponList = ref([])
const merchantList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    mid: null,
    type: null,
    start: null,
    isend: null,
    num: null,
    size: null,
    expirationStart: null,
    expirationEnd: null,
    status: null,
    name: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)
/**
 * 根据类型值获取类型名称
 * @param {string} type - 类型值
 * @returns {string} 类型名称
 */
function getTypeName(type) {
  const typeMap = {
    discount: '折扣券',
    fullReduction: '满减券',
    other: '其他'
  }
  return typeMap[type] || '未知类型'
}

/**
 * 根据类型值获取标签类型
 * @param {string} type - 类型值
 * @returns {string} 标签类型
 */
function getTypeTagType(type) {
  const typeTagMap = {
    discount: 'primary',
    fullReduction: 'success',
    other: 'info'
  }
  return typeTagMap[type] || 'info'
}

/**
 * 根据状态值获取状态名称
 * @param {string} status - 状态值
 * @returns {string} 状态名称
 */
function getStatusName(status) {
  const statusMap = {
    0: '未开始',
    1: '进行中',
    2: '已结束'
  }
  return statusMap[status] || '未知状态'
}

/**
 * 根据状态值获取标签类型
 * @param {string} status - 状态值
 * @returns {string} 标签类型
 */
function getStatusTagType(status) {
  const statusTagMap = {
    0: 'danger',
    1: 'success',
    2: 'warning'
  }
  return statusTagMap[status] || 'info'
}
/** 查询商优惠券列表 */
function getList() {
  loading.value = true
  listCoupon(queryParams.value).then(response => {
    couponList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
// 查询商户列表
function getMerchantList() {
  loading.value = true
  listMerchant(queryParams.value).then(response => {
    merchantList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getMerchantNameById(mid) {
  const merchant = merchantList.value.find(m => m.id == mid)
  return merchant ? merchant.name : '未知商家'
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}
/**
 * 填充优惠券名
 * @param {number} mid - 商家 ID
 */
function fillCouponName(mid) {
  const merchant = merchantList.value.find(m => m.id === mid)
  if (merchant) {
    form.value.name = merchant.name
  }
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    mid: null,
    type: null,
    discount: null,
    triggerMoney: null,
    preferentialMoney: null,
    start: null,
    isend: null,
    num: null,
    size: null,
    expirationStart: null,
    expirationEnd: null,
    status: null,
    name: null
  }
  proxy.resetForm("couponRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商优惠券"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getCoupon(_id).then(response => {
    const data = response.data
    // 复制原始数据
    form.value = { ...data }
    // 确保状态值是数字类型
    form.value.status = String(data.status)
    open.value = true
    title.value = "修改商优惠券"
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["couponRef"].validate(valid => {
    if (valid) {
      // 确保提交的状态值是数字类型
      if (form.value.status !== null && form.value.status !== undefined) {
        form.value.status = parseInt(form.value.status, 10)
      }
      if (form.value.id != null) {
        updateCoupon(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCoupon(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除商优惠券编号为"' + _ids + '"的数据项？').then(function () {
    return delCoupon(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('chy/coupon/export', {
    ...queryParams.value
  }, `coupon_${new Date().getTime()}.xlsx`)
}

getList()
getMerchantList()
</script>
